require(['jquery',
         'global',
         'module/util',
         'bootbox.min',
         'module/ajax',
         'jquery.ui',
         'jquery.validate',
         'bootstrap',
         'pixeladmin'], 
         function($, global, util, bootbox,_){
	window.PixelAdmin.start();
    //#J_permissionContainer
    //.J_roleList
    //.J_save
	//数据权限管理，用户组列表
	 $(document).on('change','.J_workgroupList',function(e){
	        var self = $(e.currentTarget);
	        if(self.val()=="0"){
	        }
	        $.ajax({
	            url: global.context+"/web/workgroup/getOrginRefs",
	            type: "get",
	            cache:false,
	            data: {
	                groupId:$(e.currentTarget).val()
	            },
	            dataType: "json",
	            success: function(result) {
	                if(result){
	                    if(result.code == "ACK" ||result.code == "ACK_NO_MESSAGE"){
	                        var originalPerms = result.data;
	                        var permissionsContainer = $('#chosen-content');
	                        permissionsContainer.empty();
	                       
	                        $(":checkbox","#panel-program-content").prop('checked',false);
	                        if(originalPerms!=null && originalPerms.length>0){
	                            for(var i=0;i<originalPerms.length;i++){
	                               //$("#qb_"+originalPerms[i].refId)[0].checked=true;
	                            	permissionsContainer.append('<label class="w-3 col-sm-6"><input id="qs_chosen_'+originalPerms[i].refId+'" type="checkbox" class="chosen" style="float: left;" value="'+originalPerms[i].refId+'" /> <span style="margin: 2px 0 2px 5px; float: left;">'+originalPerms[i].refContent+'</span></label>');
	                            	$("#qs_chosen_"+originalPerms[i].refId)[0].checked=true;
	                            	$("#qs_"+originalPerms[i].refId)[0].checked=true;
	                            }
	                        }
	                    }
	                }
	            }
	        });
	    });
	 //用户组管理，用户组列表
    $(document).on('change','.J_groupUserList',function(e){
        var self = $(e.currentTarget);
        if(self.val()=="0"){
        }
        $.ajax({
            url: global.context+"/web/workgroup/getOrginUsers",
            type: "get",
            cache:false,
            data: {
                groupId:$(e.currentTarget).val()
            },
            dataType: "json",
            success: function(result) {
                if(result){
                    if(result.code == "ACK" ||result.code == "ACK_NO_MESSAGE"){
                        var originalUsers = result.data;
                        var permissionsContainer = $('#chosen-user-content');
                        permissionsContainer.empty();
                       
                        if(originalUsers!=null && originalUsers.length>0){
                            for(var i=0;i<originalUsers.length;i++){
                               //$("#qb_"+originalPerms[i].refId)[0].checked=true;
                            	permissionsContainer.append('<label class="w-3 col-sm-3 col-xs-6 "><input id="user_'+originalUsers[i].id+'" type="checkbox" class="userchosen" style="float: left;" value="'+originalUsers[i].id+'" /> <span style="margin: 2px 0 2px 5px; float: left;">'+originalUsers[i].name+'</span></label>');
                            	$("#user_"+originalUsers[i].id)[0].checked=true;
                            }
                        }
                    }
                }
            }
        });
    });
    //教材列表,查询原始权限
	 $(document).on('change','#J_tb_workgroup',function(e){
	        var self = $(e.currentTarget);
	        var subject = $("#J_tb_workgroup option:selected").data("subject");
	        // 根据选中用户组所属科目 设置科目值
	        $("#tb_subject").val(subject);
	        
	        $.ajax({
	            url: global.context+"/web/workgroup/gettextbooks",
	            type: "get",
	            cache:false,
	            data: {
	            	subject:subject,
	                groupId:$(e.currentTarget).val()
	            },
	            dataType: "json",
	            success: function(result) {
	                if(result){
	                    if(result.code == "ACK" ||result.code == "ACK_NO_MESSAGE"){
	                        var originalPerms = result.data;
	                        var html;
	                        // 清空教材列表
	                        $("#panel-textbook-content").empty();
	                        // 重新设置教材列表
	                        $.each(originalPerms.textBookList,function(i,v){
	                        	html = '<label class="w-3 col-sm-6"> <input id="tb_'+ v.id 
	                        	+'" type="checkbox" style="float: left;" value="'+ v.id 
	                        	+'" class="unchosen" />';
								if(v.value.length > 22){
									html += '<span style="margin: 2px 0 2px 5px; float: left;" data-toggle="tooltip"' 
										+'data-placement="bottom" title="'+ v.value +'">' + v.value.substring(0,22) + '...</span>';
								} else {
									html += '<span style="margin: 2px 0 2px 5px; float: left;">'+ v.value +'</span>' ;
								}
								$("#panel-textbook-content").append(html);
	                        });
	                        
	                        
	                        var textBookList=originalPerms.originalPerms;
	                        var permissionsContainer = $('#textbook_chosen_content');
	                        permissionsContainer.empty();
	                        $(":checkbox","#panel-textbook-content").prop('checked',false);
	                        if(textBookList!=null && textBookList.length>0){
	                            for(var i=0;i<textBookList.length;i++){
	                            	permissionsContainer.append('<label class="w-3 col-sm-6"><input id="tb_chosen_'+textBookList[i].refId+'" type="checkbox" class="chosen" style="float: left;" value="'+textBookList[i].refId+'" /> <span style="margin: 2px 0 2px 5px; float: left;">'+textBookList[i].refContent+'</span></label>');
	                            	$("#tb_chosen_"+textBookList[i].refId)[0].checked=true;
	                            	if($("#tb_"+textBookList[i].refId)){
	                            		$("#tb_"+textBookList[i].refId)[0].checked=true;
	                            	}
	                            }
	                        }
	                    }
	                }
	            }
	        });
	    });
  
	//点击新建按钮时，显示新建窗口
	$(document).on('click', '#createWorkGroup', function(){
		$("#wg_description").parent().show();
		$("#wg_name").removeAttr("readonly");
		
		adminUserForm.resetForm();
		$("#qbankModal").find("input[type='text'],select").removeClass('highlight-error');
		$("#myform input").val('');
		$(".modal-title").html("新建用户组");
		$('#myform').attr('action' , global.context+'/web/workgroup/doAdd');
		$('#myform select option:first-child').each(function(){
			$(this).parent().val($(this).val());
		});
		$('#qbankModal').modal('show');
	});
	
	//点击修改按钮时，显示修改窗口
	$(document).on('click', '#editSubject', function(){
		var sel = $(".J_groupUserList option:selected");
		
		if(sel.val() == 0){
			$.pnotify({
				type: 'error',
				text: '请先选择一个用户组'
			});
			return;
		}
		
		$("#wg_id").val(sel.val());
		$("#wg_name").val(sel.text());
		$("#wg_subject").val(sel.data("subject"));
		
		$("#wg_description").parent().hide();
		$("#wg_name").attr("readonly","readonly");
		
		$("#qbankModal").find("input[type='text'],select").removeClass('highlight-error');
		$(".modal-title").html("修改用户组科目");
		$('#myform').attr('action' , global.context+'/web/workgroup/doAdd');
		$('#qbankModal').modal('show');
	});
	
    //查询题库
	 $(document).on('click','#searchquestionsource',function(e){
		 var me = $(this);
		 me.attr('disabled',true);
    	 var perContainer = $('#panel-program-content');
    	 var groupId=$("#workgroupuser").val()
    	 perContainer.empty();
        $.ajax({
            url: global.context+"/web/workgroup/getquestionsources",
            type: "get",
            data: {
            	subject:$('#subject').val(),
            	grade:$('#grade').val(),
            	term:$('#term').val(),
            	edition:$('#edition').val(),
            	areaId:$('#areaId').val(),
            	groupId:groupId
            },
            contentType : 'application/json; charset=UTF-8',
            dataType: "json",
            error: function(request) {
                me.attr('disabled',false);
            },
            success: function(result) {
                if(result){
                    if(result.code == "ACK" ||result.code == "ACK_NO_MESSAGE"){
                        var data = result.data;
                        var permissionsContainer1 = $('#panel-program-content');
                        $.each(data.qsList,function(i,v){
                        	if(v.name.length>22){
                    			permissionsContainer1.append ('<label class="w-3 col-sm-6"><input id="qs_'+v.id+'" type="checkbox" class="unchosen" style="float: left;" value="'+v.id+'" /> <span style="margin: 2px 0 2px 5px; float: left;" title='+v.name+'>'+v.name.substring(0,22)+'...'+'</span></label>')
                    		}else{
                    			permissionsContainer1.append ('<label class="w-3 col-sm-6"><input id="qs_'+v.id+'" type="checkbox" class="unchosen" style="float: left;" value="'+v.id+'" /> <span style="margin: 2px 0 2px 5px; float: left;" >'+v.name+'</span></label>')
                    		}
                        });
                        
                        $.each(data.originalPerms,function(i,v){
                    	   var ck = $("#qs_"+v.refId);
                    	   if(ck){
                    		  ck.attr("checked",true);
                    	   }
                        });
                    }
                }
                me.attr('disabled',false);
            }
        });
    });
	 
	 //查询教材
	 $(document).on('click','#searchtextbook',function(e){
    	 var perContainer = $('#panel-textbook-content');
    	 var groupId=$("#J_tb_workgroup").val()
    	 perContainer.empty();
        $.ajax({
            url: global.context+"/web/workgroup/gettextbooks",
            type: "get",
            data: {
            	subject:$('#tb_subject').val(),
            	grade:$('#tb_grade').val(),
            	term:$('#tb_term').val(),
            	edition:$('#tb_edition').val(),
            	groupId:groupId
            },
            contentType : 'application/json; charset=UTF-8',
            dataType: "json",
            success: function(result) {
                if(result){
                    if(result.code != "NACK"){
                        var data = result.data;
                        var tbList=data.textBookList;
                        var originalPerms=data.originalPerms;
                        if(tbList!=null && tbList.length>0){
                        	for(var i=0;i<tbList.length;i++){
                        		if(tbList[i].value.length>22){
                        			perContainer.append ('<label class="w-3 col-sm-6"><input id="qs_'+tbList[i].id+'" type="checkbox" class="unchosen" style="float: left;" value="'+tbList[i].id+'" /> <span style="margin: 2px 0 2px 5px; float: left;" title='+tbList[i].value+'>'+tbList[i].value.substring(0,22)+'...'+'</span></label>')
                        		}else{
                        			perContainer.append ('<label class="w-3 col-sm-6"><input id="qs_'+tbList[i].id+'" type="checkbox" class="unchosen" style="float: left;" value="'+tbList[i].id+'" /> <span style="margin: 2px 0 2px 5px; float: left;">'+tbList[i].value+'</span></label>')
                        		}
                        	}
                        }
                       
                    }
                }
            }
        });
    });
	 //重置
	 $(".do-reset").on("click",function(){
			$('.panel-body input[type=text]').val('');	
			$('.panel-body select option:first-child').each(function(){
				$(this).parent().val($(this).val());
			});
			
		});
    //题库列表，题库信息
    $("#J_permissionContainer1").on('click','.unchosen',function(e){
        var permissionsContainer = $('#chosen-content');
        var refId=$(this).val();
        var value=$(this).next().html();
        var choseninp=$("#qs_chosen_"+refId);
        if(choseninp.length<=0){
        	permissionsContainer.append('<label class="w-3 col-sm-6"><input id="qs_chosen_'+refId+'" type="checkbox" class="chosen" style="float: left;" value="'+refId+'" checked/> <span style="margin: 2px 0 2px 5px; float: left;">'+value+'</span></label>');
        }else{
        	choseninp.parent().remove();
        }
        
      });
       //已选权限，题库信息
       $("#J_permissionContainer_chosen").on('click','.chosen',function(e){
    	   var value=$(this).attr("id");
    	   value=value.split("_");
           //$(this).next().remove();
           //$(this).prev().remove();
           $(this).parent().remove();
           $("#qs_"+value[2])[0].checked=false;
           
         });
       
     //全选
		$("a.check_all").click(function(){
			var divpanel=$(this).parent().parent().parent().find("input[type=checkbox]");
			divpanel.each(function(){
				if(!this.checked) {
	                $(this).trigger("click");
	                this.checked = true;
				}
	        });
	    })
	    //反选
	    $("a.switch").click(function(){
	    	var divpanel=$(this).parent().parent().parent().find("input[type=checkbox]");
	    	divpanel.each(function(){
	            if(this.checked) {
	            	$(this).trigger("click");
	                this.checked = false;
	            } else {
	            	$(this).trigger("click");
	                this.checked = true;
	            }
	        });
	    });
     //待选教材列表 勾选事件
       $("#panel-textbook-content").on('click','.unchosen',function(e){
           var permissionsContainer = $('#textbook_chosen_content');
           var refId=$(this).val();
           var value=$(this).next().html();
           var choseninp=$("#tb_chosen_"+refId);
           //var ckx=$('.unchosen').find('input[type=checkbox]');
           if(choseninp.length<=0){
           	permissionsContainer.append('<label class="w-3 col-sm-6"><input id="tb_chosen_'+refId+'" type="checkbox" class="chosen" style="float: left;" value="'+refId+'" checked/> <span style="margin: 2px 0 2px 5px; float: left;">'+value+'</span></label>');
           	choseninp.attr('disabled',true);
           	$("input[type='checkbox']").attr('disabled',true);
           }else{
           	choseninp.parent().remove();
           }
           choseninp.attr('disabled',false);
           $("input[type='checkbox']").attr('disabled',false);
         });
          //已选教材信息
          $("#J_textbook_chosen").on('click','.chosen',function(e){
       	   var value=$(this).attr("id");
       	   value=value.split("_");
              $(this).parent().remove();
              $("#tb_"+value[2])[0].checked=false;
            }); 
       //已选用户
       $("#J_user_chosen").on('click','.userchosen',function(e){
           $(this).parent().remove();
         });
    //保存
    $(document).on('click','.J_workgroupdatasave',function(e){
        var self = $(e.currentTarget);
        if(self.hasClass('disabled')){
            return;
        }
        var workGroupId = $('.J_workgroupList').val();
        if(workGroupId=="0"){
            $.growl.warning({ 
                title:"提示",
                message: "请选择用户组。" 
            });
            return;
        }
        var permissions = $('#J_permissionContainer_chosen').find('input[type=checkbox]');
        var checked = permissions.filter(':checked');
        var grantedPermissions = [];
        if(checked.length>0){
            for(var i=0;i<checked.length;i++){
                grantedPermissions.push(checked.eq(i).val());
            }
        }

        bootbox.confirm({
            buttons: {  
                confirm: {  
                    label: '确认',  
                    className: 'btn-myStyle'  
                },  
                cancel: {  
                    label: '取消',  
                    className: 'btn-default'  
                }  
             },  
            message: "确定要保存吗?",
            callback: function(isOk) {
                if(isOk){
                    $.ajax({
                        url: global.context+'/web/workgroup/assignperms',
                        type: "POST",
                        cache:false,
                        data: JSON.stringify({
                        	workGroupId:workGroupId,
                        	refId:grantedPermissions.join(',')
                        }),
                        beforeSend:function(){
                            self.addClass('disabled');
                        },
                        dataType: "json",
                        contentType: 'application/json;charset=utf-8',
                        success: function(result) {
                            if(result){
                                if(result.code == "ACK"||result.code == "ACK_NO_MESSAGE"){
                                    //var data = result.data;
                                }else{
                                }
                            }
                        },
                        complete:function(){
                            self.removeClass('disabled');
                        }
                    });
                }
            },
            className: "bootbox-sm"
        });
        
    });
    
    $(document).on('click','#userGroupName',function(e){
    	$('#headName').html('<i class="fa fa-th-large page-header-icon"></i>用户组管理');
    });
    $(document).on('click','#manageName',function(e){
    	$('#headName').html('<i class="fa fa-th-large page-header-icon"></i>题库权限管理');
    });
    $(document).on('click','#textbookName',function(e){
    	$('#headName').html('<i class="fa fa-th-large page-header-icon"></i>教材权限管理');
    });
    
    //用户组的分发，保存
    $(document).on('click','.J_usergroupsave',function(e){
        var self = $(e.currentTarget);
        if(self.hasClass('disabled')){
            return;
        }
        var workGroupId = $('.J_groupUserList').val();
        if(workGroupId=="0"){
            $.growl.warning({ 
                title:"提示",
                message: "请选择用户组。" 
            });
            return;
        }
        var permissions = $('#J_user_chosen').find('input[type=checkbox]');
        var checked = permissions.filter(':checked');
        var grantedPermissions = [];
        if(checked.length>0){
            for(var i=0;i<checked.length;i++){
                grantedPermissions.push(checked.eq(i).val());
            }
        }

        bootbox.confirm({
            buttons: {  
                confirm: {  
                    label: '确认',  
                    className: 'btn-myStyle'  
                },  
                cancel: {  
                    label: '取消',  
                    className: 'btn-default'  
                }  
             },  
            message: "确定要保存吗?",
            callback: function(isOk) {
                if(isOk){
                    $.ajax({
                        url: global.context+'/web/workgroup/assignusers',
                        type: "POST",
                        cache:false,
                        data: JSON.stringify({
                        	workGroupId:workGroupId,
                            userId:grantedPermissions.join(',')
                        }),
                        beforeSend:function(){
                            self.addClass('disabled');
                        },
                        dataType: "json",
                        contentType: 'application/json;charset=utf-8',
                        success: function(result) {
                            if(result){
                                if(result.code == "ACK"||result.code == "ACK_NO_MESSAGE"){
                                    //var data = result.data;
                                }else{
                                }
                            }
                        },
                        complete:function(){
                            self.removeClass('disabled');
                        }
                    });
                }
            },
            className: "bootbox-sm"
        });
        
    });
    
    //教材权限保存
    $(document).on('click','.J_textbook_save',function(e){
        var self = $(e.currentTarget);
        var workGroupId = $('#J_tb_workgroup').val();
        if(workGroupId=="0"){
            $.growl.warning({ 
                title:"提示",
                message: "请选择用户组。" 
            });
            return;
        }
        var permissions = $('#textbook_chosen_content').find('input[type=checkbox]');
        var checked = permissions.filter(':checked');
        var grantedPermissions = [];
        if(checked.length>0){
            for(var i=0;i<checked.length;i++){
                grantedPermissions.push(checked.eq(i).val());
            }
        }
        bootbox.confirm({
            buttons: {  
                confirm: {  
                    label: '确认',  
                    className: 'btn-myStyle'  
                },  
                cancel: {  
                    label: '取消',  
                    className: 'btn-default'  
                }  
             },  
            message: "确定要保存吗?",
            callback: function(isOk) {
                if(isOk){
                    $.ajax({
                        url: global.context+'/web/workgroup/assignTextBooks',
                        type: "POST",
                        cache:false,
                        data: JSON.stringify({
                        	workGroupId:workGroupId,
                        	refId:grantedPermissions.join(',')
                        }),
                        dataType: "json",
                        contentType: 'application/json;charset=utf-8',
                        success: function(result) {
                            if(result){
                                if(result.code!= "NACK"){
                                    //var data = result.data;
                                }else{
                                }
                            }
                        }
                    });
                }
            },
            className: "bootbox-sm"
        });
        
    });
  //表单校验加提交
	var adminUserForm = $('#myform').validate({
		onkeyup : false,
		rules:{
			name:{
				required: true,
				rangelength: [2,30],
            },
            description:{
				required: true,
				rangelength: [2,30],
            }
	    },
	    messages : {
	    	name:{
	    		  required: "名称不能为空",
	    		  rangelength : $.format("名称长度：{0}-{1}个字符")
	        },
	        description:{
	    		  required: "描述不能为空",
	    		  rangelength : $.format("描述长度：{0}-{1}个字符")
	        }
	    },
		
		submitHandler: function(form) {
			util.ajax_submit(form).complete(function(xhr) {
				var result = $.parseJSON(xhr.responseText);
				if(result.code=="ACK"){
					window.location.reload();
				}
				$("#qbankModal").modal('hide');
				$("#qbankModal input[type='text']").val('');
				
			});
	    },
	    errorPlacement:function(error, element){//自定义错误提示放置的位置
	    	var $errorPanel = '<div class="validate-error-panel"></div>';
	    	element.closest(".info_item").after($errorPanel);
	    	error.appendTo(element.closest(".info_item").next('.validate-error-panel'));
	    },
	    highlight: function(element, errorClass) {  
	    	$(element).addClass('highlight-error');//未通过验证的元素高亮
        },
        unhighlight: function(element, errorClass) {  
	    	$(element).removeClass('highlight-error');//通过验证去掉高亮
        },
        success: function(label) {  
        }  
	});
	
	//关闭modal框
	$("#qbankModal").on('click','.close',function(){
		adminUserForm.resetForm();
		$("#qbankModal").find("input[type='text'],select").removeClass('highlight-error');
	});

    
    /*自动填充框*/
    $('#tags').autocomplete({
    	        		source: function (request, response) {
    	        			
    	        			$.ajax({
    	        				url: global.context+'/web/workgroup/getusers',
    	        				type:"POST",
    	        				dataType: "json",
    	        				success: function(result) {
    	        					var data = result.data;
    	        					var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i");

    	    	        	        response($.grep(data, function (value) {
    	    	        	            return matcher.test(value.name)||matcher.test(value.username);
    	    	        	        }));
    	        				}
    	        			})
    	        			
    	        	        
    	        	    },
    	    			select: function( event, ui ) {
    	    		        $( "#tags" ).val( ui.item.name).data('id',ui.item.id);
    	    		        var userContainer = $('#chosen-user-content');
    	    		        var refId=ui.item.id;
    	    		        var value=ui.item.name;
    	    		        var choseninp=$("#user_"+refId);
    	    		        if(choseninp.length<=0)
    	    		        userContainer.append('<label class="w-3 col-sm-3 col-xs-6"><input id="user_'+refId+'" type="checkbox"class="userchosen" style="float: left;" value="'+refId+'" checked/> <span style="margin: 2px 0 2px 5px; float: left;">'+value+'</span></label>');
    	    		        return false;
    	    		    },
    	    	    }).data( "ui-autocomplete" )._renderItem = function( ul, item ) {
    	        		return $( "<li></li>" ).data("item.autocomplete", item)
    	                .append( "<a>"+"姓名： " + item.name +"&nbsp;&nbsp;&nbsp;用户名："+ item.username +"</a>")
    	                .appendTo( ul );
    	        	};
});